package com.cskaoyan.mall.cart.controller;

import com.cskaoyan.mall.cart.api.dto.CartInfoDTO;
import com.cskaoyan.mall.cart.service.CartService;
import com.cskaoyan.mall.common.result.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
public class CartController {

    @Autowired
    CartService cartService;

    @GetMapping("/cart/add/{skuId}/{skuNum}")
    public Result addToCart(@PathVariable("skuId")Long skuId, @PathVariable("skuNum")int skuNum, HttpServletRequest httpServletRequest){
        //获取用户id，如果未登录，就获取临时id
        String userId=getUserId(httpServletRequest);
        cartService.addToCart(skuId,userId,skuNum);
        return Result.ok();
    }

    @GetMapping("/cart")
    public Result cart(HttpServletRequest httpServletRequest){
        String userId = httpServletRequest.getHeader("userId");
        String userTempId=httpServletRequest.getHeader("userTempId");
        List<CartInfoDTO> cartList = cartService.getCartList(userId, userTempId);
        return Result.ok(cartList);

    }

    @PutMapping("/cart/check/{skuId}/{isChecked}")
    public Result checkCart(@PathVariable("skuId")Long skuId,@PathVariable("isChecked")int isChecked,HttpServletRequest httpServletRequest){
        String userId=getUserId(httpServletRequest);
        cartService.checkCart(userId,isChecked,skuId);
        return Result.ok();

    }

    @DeleteMapping("/cart/{skuId}")
    public Result deleteCart(@PathVariable("skuId") Long skuId,HttpServletRequest httpServletRequest){
        String userId=getUserId(httpServletRequest);
        cartService.deleteCart(skuId,userId);
        return Result.ok();
    }

    @DeleteMapping("/cart/checked")
    public Result deleteChecked(HttpServletRequest httpServletRequest){
        String userId=getUserId(httpServletRequest);
        cartService.deleteChecked(userId);
        return Result.ok();

    }

    public String getUserId(HttpServletRequest httpServletRequest){
        String userId = httpServletRequest.getHeader("userId");
        if (StringUtils.isBlank(userId)){
            userId=httpServletRequest.getHeader("userTempId");
        }
        return userId;
    }



}
